// 05shoppingMall/shoppingMall.js
var co = require('../resource/js/common.js')
var app = getApp()
var _this
var pgno = 1 //分页页码
var orderKey = '' //排序字段
var products_category = '' //商品分类id
var count = 0 //点击价格次数
var order_by = '' //排序类型
var product_count = 0 //加入购物车商品数量
var upCount = 0 //收起轮播图
var sortCount = 0
Page({
   /*页面的初始数据*/
   data: {
      shop_info: '',
      realHeight: '',
      scrollHeight: '',
      Image: '', // 商店轮播图
      Products: [], // 商品数据
      isHide: false,
      isShow: '',
      isActive: null, // 切换sort样式
      isSortActive: null,
      isUp: false,
      isDown: false,
      isLoad: false,
      searchInfo: '', //搜索商家
      tempSearchInfo: '',
      // 添加购物车显示
      isCart: '',
      cList: [],
      // 返回顶部
      returnTop: '',
      // 是否有商品属性
      skuList: [], //商品属性
      skuvaList: [], //商品属性值
      productSku: [],
      kName: '',
      idx: '',
      openSku: false,
      // 向上按钮
      isRetTop: false,
      // 收起轮播图
      animationData: '',
      scrollY: '',
      rotate: '0deg',
      skuId: [], //选中的规格样式
      skuPrice: '' //选中规格的价格
   },
   /*生命周期函数--监听页面加载*/
   onLoad: function(options) {
      _this = this
      var Biz_ID = options.Biz_ID //获取传递的商店id
      //获取设备高度
      var rt = wx.getSystemInfoSync().windowHeight - 320
      this.setData({
         Biz_ID: Biz_ID,
         realHeight: rt,
      })
      this.getSort()
      this.getShopInfo()
      // 转发获取群信息
      wx.showShareMenu({
         withShareTicket: true
      })
      //将邀请人ID保存全局变量
      if (options.User_ID) {
         wx.setStorageSync('Owner_Id', options.User_ID)
      }
      console.log('【商家页参数options】==', options)
      if (app.Data.userInfos == '') {
         app.loginStatic()
      }
      // console.log('【商家页参数options】==', options)
   },
   // 隐藏显示轮播图
   upSwiper: function() {
      var rotate
      var rh = this.data.realHeight // 获取scroll-view高度
      var animation = wx.createAnimation({ // 创建轮播图动画
         duration: 400,
         timingFunction: 'linear',
      })
      this.animation = animation
      var scrollY = wx.createAnimation({ // 创建scroll-view动画
         duration: 400,
         timingFunction: 'linear',
      })
      this.scrollY = scrollY
      if (upCount % 2 == 0) { // 点击判断
         rotate = '180deg'
         upCount++
         animation.height(0).step()
         scrollY.height(rh + 200).step()
      } else {
         rotate = '0deg'
         upCount++
         animation.height(200).step()
         scrollY.height(rh).step()
      }
      this.setData({
         rotate: rotate,
         animationData: animation.export(),
         scrollY: scrollY.export(),
      })
   },
   // 点击搜索商品
   searchProduct: function(e) {
      var info = e.detail.value
      this.setData({
         searchInfo: info,
         tempSearchInfo: info
      })
      _this.data.Products = []
      pgno = 1
      this.searchProducts(info)
   },
   // 搜索商品
   searchProducts(info) {
      var param = {
         Biz_ID: 91,
         keyword: info,
         pageNo: pgno,
         orderKey: orderKey,
         orderBy: order_by
      }
      console.log('param', param)
      co.getMealApi('jyhs/Prdmg/getList', param, function(res) {
         // console.log("【搜索到的商品】===", res.data)
         if (res.code == 0) {
            var len = res.data.length
            var pList = _this.data.Products
            for (var i = 0; i < len; i++) {
               pList.push(res.data[i])
            }
            _this.setData({
               Products: pList
            })
         } else {
            co.modal(res.msg)
            _this.setData({
               tempSearchInfo: ''
            })
         }
      })
   },
   // 商品排序
   sortProducts: function(e) {
      var id = e.currentTarget.id
      console.log('e', e)
      var up
      var down
      if (id == '0') {
         orderKey = 'Products_Sales'
         // 清除价格排序样式
         up = false
         down = false
         order_by = ''
      } else if (id == '1') {
         orderKey = 'Products_IsNew'
         // 清除价格排序样式
         up = false
         down = false
         order_by = ''
      } else if (id == '2') {
         orderKey = 'Products_PriceX'
         if (count % 2 == 0) {
            up = true
            down = false
            order_by = 'desc'
         } else {
            up = false
            down = true
            order_by = 'asc'
         }
         count++
      }
      this.setData({
         isActive: id,
         isUp: up,
         isDown: down,
         returnTop: 0
      })
      console.log(1)
      // 判断是否有搜索商品
      if (this.data.tempSearchInfo == '') {
         console.log(2)
         this.clear() //清空并获取商品
      } else {
         console.log(3)
         _this.setData({
            Products: []
         })
         var info = this.data.tempSearchInfo
         console.log('tempSearchInfo===', this.data.tempSearchInfo)
         this.searchProducts(info)
      }
   },
   // 点击获取商品
   acquireProducts: function(e) {
      var index = e.currentTarget.id
      var p_id = e.currentTarget.dataset.cateid
      orderKey = '' //清除排序id
      var isActive //标签栏点击背景色
      products_category = p_id
      this.clear() //清空并获取商品
      this.setData({
         isSortActive: index,
         isActive: 4,
         returnTop: 0,
         isUp: false,
         isDown: false,
         isLoad: false,
         // 清空商品属性及属性值
         skuList: [],
         skuvaList: [],
      })
   },
   // 清空商品数组及请求页面
   clear() {
      this.setData({
         tempSearchInfo: [],
         Products: []
      })
      pgno = 1
      _this.getProducts() //获取商品
   },
   // 滚动商品展示也隐藏样式
   scollBottom: function(e) {
      this.setData({
         scrollHeight: e.detail.scrollHeight
      })
      var scrollTop = e.detail.scrollTop //获取滚动条到顶部距离
      var rh = this.data.realHeight //获取scorll-view高度
      var height = e.detail.scrollHeight //获取滚动区域商品高度
      if (scrollTop >= height - rh) { //判断滚动条到底时
         pgno++
         if (this.data.tempSearchInfo != '') { //判断是否有搜索商品
            this.data.Products = []
            pgno = 1
            var info = this.data.tempSearchInfo
            this.searchProducts(info)
         } else {
            this.getProducts()
            console.log("2222")
         }
      }
      if (scrollTop >= 100) {
         this.setData({
            isRetTop: true
         })
      } else {
         this.setData({
            isRetTop: false
         })
      }
   },
   // 没有属性时添加购物车
   addCart: function(e) {
      // console.log("【获取商品id】===", e.currentTarget.dataset.idx)
      if (app.Data.userInfos == '') {
         wx.navigateTo({
            url: '/04myCenter/myCenter',
         })
      } else {
         var e_cT = e.currentTarget
         var idx = e_cT.dataset.idx //所在数组位置
         var sList = this.data.skuList //商品属性
         var psList = this.data.productSku //存入商品属性
         var n = []
         // 判断属性是否为空
         if (sList[idx] != '') {
            var k = this.data.kName
            var list
            for (var key in sList[idx]) {
               k = key //key值名称
               list = sList[idx][key]
            }
            this.setData({
               openSku: true,
               productSku: list,
               kName: k,
               idx: idx
            })
         } else {
            var param = {
               User_ID: app.Data.userInfos.User_ID,
               Product_ID: e_cT.id, //商品id
               Biz_ID: this.data.Biz_ID,
               Sku_ID: 0,
               QTY: 1
            }
            this.doShoppingCart(param, idx)
         }
      }
   },
   // 关闭属性选择窗口
   closeSku: function() {
      this.setData({
         openSku: false
      })
   },
   // 返回顶部
   returnTop: function() {
      this.setData({
         returnTop: 0
      })
   },
   // 进入购物车
   returnCart: function() {
      wx.switchTab({
         url: '/06shoppingCart/shoppingCart',
      })
   },
   // 选择属性变色
   selectAttribute: function(e) {
      var id = e.currentTarget.dataset.sindex
      var skuList = _this.data.skuList
      var price
      for (var i = 0; i < skuList[this.data.idx].length; i++) {
         if (id == i) {
            price = skuList[this.data.idx][i].Products_PriceX
         }
      }
      _this.setData({
         id: id,
         skuPrice: price
      })
   },
   // 选择属性后添加购物车
   attributeAddCart: function(e) {
      var url = 'jyhs/Cartmg/productsToShopCart'
      var sIndex = this.data.idx
      var index = this.data.id
      console.log('111this.data', app.Data)
      var select = this.data.Products[sIndex]
      var cart = {
         Products_ID: select.Products_ID,
         Products_Photo: select.Products_JSON.ImgPath[0],
         Products_Name: select.Products_Name,
         Products_Price: select.sku_list[index].Products_PriceX,
         num: 1,
         sku_name: select.sku_list[index].Sku_Name,
         sku_id: index,
         Biz_ID: "91",
         UserName: app.Data.userInfo.User_NickName,
         unionid: app.Data.userInfo.unionid
      }
      console.log('carlist', cart)
      // 加入购物车时判断用户是否登录
      if (co.empty(app.Data.userInfo.User_ID)) {
         co.toastAllText("请先登录账号！")
      } else {
         var param = {
            User_ID: app.Data.userInfo.User_ID,
            Products: JSON.stringify(cart)
         }
         console.log('param', param)
         co.getMealApi(url, param, function(res) {
            if (res.code == 0) {
               co.toastAllText(res.msg)
               _this.closeSku()
            } else {
               co.toastAllText(res.msg)
            }
         })
      }
   },
   //处理购物车
   doShoppingCart(param, idx) {
      co.getMeallApi('product/Pmg/insertShoppingCart', param, function(res) {
         if (res.code == 0) {
            var cList = _this.data.cList
            cList[idx] = 1
            _this.setData({
               cList: cList
            })
            app.noticedShopCartReload("reload") //通知刷新
            co.toast(res.msg)
         }
      })
   },
   // 获取商品数据
   getProducts() {
      var param = {
         Biz_ID: 91,
         page: pgno,
         orderKey: orderKey,
         Products_BizCategory: products_category,
         orderBy: order_by
      }
      console.log('param-获取', param)
      co.getMealApi('jyhs/Prdmg/getList', param, function(res) {
         if (res.code == 0) {
            var len = res.data.length
            var pList = _this.data.Products
            var cList = _this.data.cList //商品是否加入购物车
            var sList = _this.data.skuList //商品属性
            var sjList = _this.data.skuvaList //商品属性值
            for (var i = 0; i < len; i++) {
               pList.push(res.data[i])
               cList.push(0)
               sList.push(res.data[i].sku_list)
               sjList.push(res.data[i].skuval)
               // 判断是否有加购商品
               if (res.data[i].is_in_shopping_cart > 0) {
                  cList[i] = 1
               }
            }
            _this.setData({
               Products: pList,
               cList: cList,
               skuList: sList,
               skuvaList: sjList,
            })
         }
         if (res.data.length < 10) {
            _this.setData({
               isLoad: true,
            })
         }
         if (res.code == 29300) {
            _this.setData({
               isLoad: true,
            })
         }
      })
   },
   // 获取商店信息
   getShopInfo() {
      var param = {
         Biz_ID: 91,
         //Skin_ID: 2
      }
      co.getShareApi('jyhs/Admin/getInfo', param, function(res) {
         if (res.code == 0) {
            _this.setData({
               shop_info: res.data,
               Image: res.data.Instore_Photos
            })
         }
      })
   },
   // 获取商店分类数据
   getSort() {
      var param = {
         Biz_ID: 91
      }
      co.getMealApi('jyhs/Prdmg/getBizCategoryList', param, function(res) {
         if (res.code == 0) {
            // 第一选项分类ID
            var sortID = res.data[0].Category_ID
            products_category = sortID,
               _this.setData({
                  Category: res.data,
                  isSortActive: 0,
               })
            // 获取第一项分类商品信息
            _this.getProducts()
         }
      })
   },
   // 卸载页面清空
   onUnload: function() {
      this.setData({
         Products: []
      })
      products_category = ''
      pgno = ''
   },
   //分享
   onShareAppMessage: function() {
      var urlParam = '?Biz_ID=' + this.data.shop_info.Biz_ID
      if (app.Data.userInfos.User_ID) {
         urlParam += '&User_ID=' + app.Data.userInfos.User_ID
      }
      return {
         title: this.data.shop_info.Biz_Account + '【本地O2O实体店】',
         path: '/05local/02shopHome/shopHome' + urlParam,
         success: function(res) {
            console.log("【分享成功res】===", res)
            var pages = getCurrentPages() //获取加载的页面
            var currentPage = pages[pages.length - 1] //获取当前页面的对象
            app.getShareInfo(res, _this.data.shop_info.Biz_Account + '-商家首页', currentPage.route)
         }
      }
   }
})